package com.xxxy.jsq.action.user;

import com.alibaba.fastjson2.JSONObject;
import com.xxxy.jsq.dao.UserDao;
import com.xxxy.jsq.model.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "getUsersServlet", value = "/getUsersServlet")
public class getUsersServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public getUsersServlet() {
        super();
        // TODO Auto-generated constructor stub
    }


    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 创建UserDao对象进行数据库访问
        UserDao dao = new UserDao();

        // 获取所有可用用户列表
        List<User> list = dao.getAllky();

        // 打印列表到控制台
        System.out.println(list);

        // 创建JSON对象
        JSONObject jo = new JSONObject();

        // 将用户列表放入JSON对象中
        jo.put("data", list);

        // 打印JSON对象到控制台
        System.out.println(jo.toString());

        // 获取响应输出流
        PrintWriter out = response.getWriter();

        // 将JSON对象输出到客户端
        out.print(jo);

        // 刷新输出流
        out.flush();

        // 关闭输出流
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
